import {
  Router
} from 'express'
import _ from 'lodash'
const router = Router()
import { signature } from '../webchat'
import mysql from '../plugs/mysql'
import axios from 'axios'
router.get('/', async (req, res, next) => {
  //判断cookie有没有，没有则需要登录，如果有，则判断数据库有没有
  let config = req.app.get('$config');
  const sign = await signature(`${config.get('appDomain')}/`);
     return res.render('index',{
        sign
      });
  if (req.cookies && req.cookies[config.get('sessIdKey')] && req.cookies[config.get('sessIdKey')] != '') {
    let myConnect = await mysql.getConnect();
    let sql = `select session_key,data from session where session_key = ${myConnect.escape(req.cookies[config.get('sessIdKey')])}`
    let sessionResult = await mysql.query(myConnect,sql);
    await mysql.release(myConnect);
    
    if(sessionResult.length){
     
      return res.render('index',{
        sign
      });
    }else{
      return res.redirect('/oauth/login?scope=snsapi_userinfo&returnUrl=/');
    }
  } else {
    return res.redirect('/oauth/login?scope=snsapi_userinfo&returnUrl=/');
  }
})
router.get('/test', async (req, res, next) => {
  //判断cookie有没有，没有则需要登录，如果有，则判断数据库有没有
  let config = req.app.get('$config');
  if (req.cookies && req.cookies[config.get('sessIdKey')] && req.cookies[config.get('sessIdKey')] != '') {
    let myConnect = await mysql.getConnect();
    let sql = `select session_key,data from session where session_key = ${myConnect.escape(req.cookies[config.get('sessIdKey')])}`
    let sessionResult = await mysql.query(myConnect,sql);
    await mysql.release(myConnect);
    if(sessionResult.length){
      return res.render('test');
    }else{
      return res.redirect('/oauth/login?scope=snsapi_userinfo&returnUrl=/test');
    }
  } else {
    return res.redirect('/oauth/login?scope=snsapi_userinfo&returnUrl=/test');
  }
})
router.get('/feihe',async(req,res,next)=>{
  return res.render('feihe');
})

export default router